﻿#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    player=nullptr;

    today=QDate::currentDate().toString("yyyy-MM-dd");
    mac=Env::getHarewareAddress();
    manager=new QNetworkAccessManager(this);
    connect(manager,&QNetworkAccessManager::finished,this,&Dialog::replyFinished);

    tmp="../tmp";
    QDir dir(tmp);
    if(dir.makeAbsolute())
        tmp=dir.path();

    local=QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation);
    sessionFile=local + SESSION_FILE;

    if(!QFile::exists(sessionFile))
        getToken();
    else
        if(!loadSession())
            getToken();
        else
            ui->status->setText("load success");
}

Dialog::~Dialog()
{
    delete ui;
}

/*
void Dialog::ping()
{
    pingReply = manager->get(QNetworkRequest(QUrl(base_url)));
    connect(pingReply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(un_reach()));
}
*/


void Dialog::initAudioRecorder()
{
    audioRecorder=new QAudioRecorder(this);

    QAudioEncoderSettings audioSettings;
    audioSettings.setCodec("audio/pcm");
    audioSettings.setQuality(QMultimedia::HighQuality);
    //   audioSettings.setSampleRate(16000);
    audioRecorder->setEncodingSettings(audioSettings);
    audioRecorder->setContainerFormat("wav");

    connect(audioRecorder,&QAudioRecorder::stateChanged,
            this,&Dialog::stateChanged);
}

bool Dialog::saveSession()
{
    if(access_token.isEmpty())
        return false;

    QDir dir(local);
    if(!dir.exists())
        dir.mkpath(local);

    QJsonObject obj;
    obj.insert("date",today);
    obj.insert("token",access_token);

    QFile file(sessionFile);
    if(file.open(QFile::WriteOnly))
    {
        QJsonDocument doc(obj);
        file.write(doc.toBinaryData());
        file.close();
        return true;
    }
    else
        return false;
}

bool Dialog::loadSession()
{
    QFile file(sessionFile);
    if(file.open(QFile::ReadOnly))
    {
        QJsonDocument doc=QJsonDocument::fromBinaryData(file.readAll());
        if(doc.isObject())
        {
            QJsonObject obj=doc.object();
            QString dateStr=obj.value("date").toString();
            QDate date=QDate::fromString(dateStr,"yyyy-MM-dd");

            if(date.daysTo(QDate::currentDate()) > 28)
                return false;
            else
            {
                access_token=obj.value("token").toString();
                return true;
            }
        }
        return false;
    }
    return false;
}

void Dialog::play(const QString &path)
{
    if(player == nullptr)
        player=new AVPlayer(this);

    player->setFile(path);
    player->play();
}

void Dialog::getToken(const QString &token_file)
{
    if(!QFile::exists(token_file))
        return;

    QSettings set(token_file,QSettings::IniFormat);
    QString API_Key=set.value("Token/API_Key").toString();
    QString Secret_Key=set.value("Token/Secret_Key").toString();
    QString url=QString(TOKEN_URL).arg(API_Key).arg(Secret_Key);
    httpGet(url);
}

void Dialog::httpGet(const QString &url)
{
    QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(url)));
    replyMap.insert(reply,R_Get);
}

void Dialog::httpPost(const QString &url, const QByteArray &data)
{
    QNetworkRequest request;
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setUrl(QUrl(url));

    QNetworkReply *reply = manager->post(request,data);
    replyMap.insert(reply,R_Post);
}

void Dialog::un_reach()
{
    pingReply->deleteLater();
    QMessageBox::critical(this,QStringLiteral("无法连接"),QStringLiteral("无法连接到服务器！"));
}

void Dialog::replyFinished(QNetworkReply *reply)
{
    if(reply == pingReply)
        return;

    if(reply->size() > 1000 )
    {
        QString uid=QUuid::createUuid().toString();
        QString fileName="../tmp/" + uid;
        QFile file(fileName);
        file.open(QFile::WriteOnly);
        file.write(reply->readAll());
        file.close();

        play(fileName);
    }
    else
    {
        R_Request request=replyMap.value(reply);
        switch (request) {
        case R_Get:
        {
            QJsonDocument doc=QJsonDocument::fromJson(reply->readAll());
            if(doc.isEmpty())
                return;

            QJsonObject obj=doc.object();
            if(obj.isEmpty())
                return;

            if(obj.contains("access_token"))
            {
                access_token=obj.value("access_token").toString();
                if(!access_token.isEmpty())
                {
                    saveSession();
                    ui->status->setText("Connection Initialized");
                }
            }
        }
            break;
        case R_Post:
        {
            QJsonDocument doc=QJsonDocument::fromJson(reply->readAll());
            qDebug() << doc.toJson(QJsonDocument::Compact);
            if(doc.isEmpty())
                return;

            QJsonObject obj=doc.object();
            if(obj.isEmpty())
                return;

            if(obj.contains("err_no"))
            {
                int code=obj.value("err_no").toInt();
                if(code == 0)
                {
                    QJsonArray array=obj.value("result").toArray();
                    qDebug() << array.size();
                    QString result=array.at(0).toString();
                    qDebug() << result;
                    ui->status->setText(result);
                }
                else
                    ui->status->setText(QString::number(code));
            }
        }
            break;
        }
    }
}
void Dialog::on_btn_submit_clicked()
{
    if(access_token.isEmpty())
        return;

    QString word=ui->word->text().trimmed();
    if(word.isEmpty())
        return;

    QString url=QString(TTS_URL).arg(word).arg(mac).arg(access_token);
    httpGet(url);
}

void Dialog::on_btn_submit2_clicked()
{
    if(access_token.isEmpty())
        return;

    QString word=ui->word->text().trimmed();
    if(word.isEmpty())
        return;

    QString url=QString(TTS2_URL).arg(word).arg(mac).arg(access_token);
    httpGet(url);
}

void Dialog::on_btn_record_clicked()
{
    recordFile = "F:/Stage/tmp/{6889f0bd-5283-41a6-b437-e2c2c9d1f0b2}.wav";
    uploadRecordFile();

    /*
    if(audioRecorder == nullptr)
        initAudioRecorder();

    detectState();
    */
}
